//
// Created by 成飞 on 2024/1/9.
//

#ifndef ORDERKV_SERVER_H
#define ORDERKV_SERVER_H

#define BATCH_SIZE 1024


#include "value_store/orderkv_w_buffer.h"
#include "lsm_tree/leveldb.h"
#include "util/bloom_filter.hpp"

namespace db {
    using std::string;
    using std::string_view;
    using std::map;
    using std::vector;
    using std::pair;
    using std::array;

    class Server {
    protected:
        int WBufferNum{};
        std::vector<vstore::WBuffer *> WBufferCluster{};
        vstore::WBuffer *pWBuffer{};
        int curWBufferInd{};
//        conf::Env env = conf::Env::instance();
        size_t threshold{};

        bloom_filter LSMTreeBloomFiler; //记录LSM-Tree中是否有addr
        lsm::LsmTree *lsmTree{};

    public:
        Server();

        bool put(std::string key, std::string val);

        std::string query(const std::string& key);

        std::vector<std::pair<std::string, std::string >> range_query(const std::string& startKey, const std::string& endKey, int len);

        std::vector<std::pair<std::string, std::string >> range_query2(const std::string& startKey, const std::string& endKey, int len);

        ~Server();

    protected:
        void init();

        static void persist_buffer(vstore::WBuffer *snapshotWBuffer) ;

        void change_ind();

        static std::string_view scan_file(meta::fid fileNo, meta::f_off startOffset, size_t scanLen);


    private:
        void basic_init();

        void lsm_init();

        void WBuffer_init();

        void daemon_init();

        void crash_check_gc();

        void crash_check_data();

        void check_size();

        void persistence(vstore::WBuffer *);

        void write_lsm(vstore::OrderkvWBuffer *snapshotWBuffer);

        inline static void find_vstore_kv(vector<pair<string , lsm::LsmRecordVal>>&,
                                                              array<lsm::ScanInfo*, FILE_NO_MAX>&,
                                                              std::vector<std::pair<std::string_view, std::string_view >>& ret);

        inline static void merge_range(vector<pair<string_view, string_view>>& wBufferRes,
                                       vector<pair<string_view, string_view>>& vstoreRes,
                                       int len,
                                       std::vector<std::pair<std::string, std::string >>& ret);


        void garbage_compute(vstore::WBuffer*);

        void garbage_monitoring();

        void gc(meta::fid);

        void bufferImage_store(vstore::WBuffer*);

        void bufferImage_load(vstore::WBuffer*);

    };
}


#endif //ORDERKV_SERVER_H
